//
//  BannerWebViewVC.m
//  HengYouCai
//
//  Created by lwj on 2017/9/22.
//  Copyright © 2017年 lwj. All rights reserved.
//

#import "BannerWebViewVC.h"
#import <WebKit/WebKit.h>
#import "AppDelegate.h"
#import "UIView+Toast.h"
#import "HengYouCai-Swift.h"
#import "PBViewController.h"

@interface BannerWebViewVC ()<WKNavigationDelegate,WKUIDelegate,WKScriptMessageHandler,UINavigationControllerDelegate,PBViewControllerDelegate,PBViewControllerDataSource>

@property (nonatomic,strong) WKWebView *wkWebView;
@property (nonatomic, copy)NSString *url;

/**
 *  进度条
 */
@property (nonatomic, strong) UIProgressView * progressView;
/**
 *  图片浏览器
 */
@property (nonatomic, strong) PBViewController * photoBrowser;
/**
 *  图片url
 */
@property (nonatomic, strong) NSURL *photoUrl;
@end

@implementation BannerWebViewVC

- (instancetype)initWithUrlStr:(NSString *)str title:(NSString *)navTitle
{
    if (self = [super init]) {
        
        self.url = str;
        
        self.navigationItem.title = navTitle;
        
    }
    return self;
}
- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    [_wkWebView removeObserver:self forKeyPath:@"estimatedProgress"];

    [_wkWebView.configuration.userContentController removeAllUserScripts];
    //_wkWebView = nil; 不能置空 否则 大转盘跳登录 回来之后不会刷新界面
//    _wkWebView = nil;
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    //因为项目一直黑色的网页返回按钮 暂时这样处理 心累
    self.navigationController.navigationBar.backIndicatorImage = [[UIImage imageNamed:@"back"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    //混编网页会包含mixApp 这个时候要把导航栏隐藏掉 因为h5自带
    self.navigationController.navigationBarHidden = [_url containsString:@"mixApp"];
    //放在这里 修复网页端未登录 跳转登录之后 返回还是未登录问题
    NSString *sessionID = [WLFileManager readUserDataForKey:kUserSessionId];
    //处理url参数问题 网址包含login的 返回界面刷新
    NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
    
    NSString *app_Version = [infoDictionary objectForKey:@"CFBundleShortVersionString"];
    if ([_url containsString:@"login"]) {
        [self loadRequestWithUrlStr:[NSString stringWithFormat:@"%@=%@",_url,sessionID]];

    }else{
        if ([_url containsString:@"?"]){//带问号
            [self loadRequestWithUrlStr:[NSString stringWithFormat:@"%@&sessionId=%@&version=%@",_url,sessionID,app_Version]];
        }else{//不带问号
            [self loadRequestWithUrlStr:[NSString stringWithFormat:@"%@?sessionId=%@&version=%@",_url,sessionID,app_Version]];
        }
    }
    ///进度条
    [self.view addSubview:self.progressView];
    [self.wkWebView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil];
    self.view.backgroundColor = [UIColor whiteColor];



}
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    self.navigationController.navigationBarHidden = NO;
    
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self.view addSubview:self.wkWebView];

    
   

  
    
    if (_isFromADGuide) {
        
        UIButton *leftBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        leftBtn.frame = CGRectMake(0, 0, 100, 40);
        [leftBtn setImage:[UIImage imageNamed:@"back"] forState:UIControlStateNormal];
        leftBtn.contentHorizontalAlignment=UIControlContentHorizontalAlignmentLeft;
        [leftBtn setImageEdgeInsets:UIEdgeInsetsMake(0,-5, 0, 0)];
        [[leftBtn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
             [(AppDelegate *)UIApplication.sharedApplication.delegate setRootVCForKeyWindowAnimation:YES tabbarSelectedIndex:0];
        }];
        
        self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:leftBtn];
    }
}

- (void)dealloc{
    if (_wkWebView) {
        [_wkWebView removeObserver:self forKeyPath:@"estimatedProgress"];
    }
}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    
    if (object == self.wkWebView && [keyPath isEqualToString:@"estimatedProgress"]) {
        CGFloat newprogress = [[change objectForKey:NSKeyValueChangeNewKey] doubleValue];
        self.progressView.hidden = NO;
        [self.progressView setProgress:newprogress animated:YES];
    }
}
- (void)loadRequestWithUrlStr:(NSString *)urlStr{
    
    NSMutableURLRequest * request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:urlStr]];
    //用户token
    NSString *userToken = [WLFileManager readUserDataForKey:kUserSessionId];
    if (userToken!=nil) {
        [request setValue:userToken forHTTPHeaderField:kUserSessionId];
    }
    //渠道码
    [request setValue:kChannel_app forHTTPHeaderField:@"appChannel"];
    //来源
    [request setValue:@"iOS" forHTTPHeaderField:@"OSType"];
    //手机型号
    [request setValue:[NSObject wl_getDeviceModel] forHTTPHeaderField:@"deviceModel"];
    //手机系统版本
    [request setValue:[[UIDevice currentDevice] systemVersion] forHTTPHeaderField:@"OSVersion"];
    //应用程序版本
    NSDictionary *dict = [[NSBundle mainBundle] infoDictionary];
    NSString *app_Version = [dict objectForKey:@"CFBundleShortVersionString"];
    [request setValue:app_Version forHTTPHeaderField:@"appVersion"];
    //MARK:网页请求默认10s
    request.timeoutInterval = 10;

    [_wkWebView loadRequest:request];
}
///创建wkWebView
- (WKWebView *)wkWebView
{
    if (!_wkWebView) {
        WKUserContentController *userContentController = [[WKUserContentController alloc] init];
        
        // 跳转首页
        [userContentController addScriptMessageHandler:self name:@"appToIndex"];
        // 跳转登录页
        [userContentController addScriptMessageHandler:self name:@"appToLogin"];
        // 跳转注册页
        [userContentController addScriptMessageHandler:self name:@"appToRegister"];
        // 跳转实名注册页
        [userContentController addScriptMessageHandler:self name:@"appToRealName"];
        // 跳转充值页
        [userContentController addScriptMessageHandler:self name:@"appToRecharge"];
        // 跳转产品列表页
        [userContentController addScriptMessageHandler:self name:@"appToGetList"];
        // 请求APP的传值
        [userContentController addScriptMessageHandler:self name:@"appAcceptVal"];
        // 向APP传值并关闭当前webView窗口
        [userContentController addScriptMessageHandler:self name:@"appPassVal"];
        // 打开app的loading
        [userContentController addScriptMessageHandler:self name:@"appOpenLoading"];
        // 关闭app的loading
        [userContentController addScriptMessageHandler:self name:@"appCloseLoading"];
        // App分享功能
        [userContentController addScriptMessageHandler:self name:@"appToShare"];
        // 刷新账户中心
        [userContentController addScriptMessageHandler:self name:@"appToAccount"];
        // 刷新账户中心
        [userContentController addScriptMessageHandler:self name:@"appCloseView"];
        [userContentController addScriptMessageHandler:self name:@"appOpenView"];
        //app分享
        [userContentController addScriptMessageHandler:self name:@"appShare"];
        // 图片放大
        [userContentController addScriptMessageHandler:self name:@"appEnlarge"];
        // 风险测评
        [userContentController addScriptMessageHandler:self name:@"appToRiskAssessment"];
        //        wkcontent.add(self as WKScriptMessageHandler, name: "appEnlarge")
        //
        WKWebViewConfiguration * config = [[WKWebViewConfiguration alloc] init];
        config.userContentController = userContentController;
        CGFloat statusH = [[UIApplication sharedApplication] statusBarFrame].size.height;
        
        if (![_url containsString:@"mixApp"]) {
            statusH = kJcwGetNavHeight();
        }
        
        _wkWebView = [[WKWebView alloc] initWithFrame:(CGRect){{0,statusH},{self.view.frame.size.width,self.view.frame.size.height-statusH}} configuration:config];
        //        _wkWebView = [[WKWebView alloc] initWithFrame:self.view.bounds configuration:config];
        if (@available(iOS 11.0, *)) {
            _wkWebView.scrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        } else {
            self.automaticallyAdjustsScrollViewInsets = NO;
        }
        _wkWebView.UIDelegate = self;
        _wkWebView.navigationDelegate = self;
    }
    return _wkWebView;
}
- (PBViewController *)photoBrowser
{
    if (!_photoBrowser) {
        _photoBrowser = [[PBViewController alloc] init];
        _photoBrowser.pb_delegate = self;
        _photoBrowser.pb_dataSource = self;
    }
    return _photoBrowser;
}
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation{
    //加载完成2秒之后隐藏进度条
    [self performSelector:@selector(hideProgress) withObject:nil afterDelay:1];
}
///加载成功失败判断  失败自动返回
- (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler{//有网 加载失败
    NSHTTPURLResponse * response = (NSHTTPURLResponse *)navigationResponse.response;
    if (response.statusCode == 200) {
        decisionHandler(WKNavigationResponsePolicyAllow);
    }else{
        decisionHandler(WKNavigationResponsePolicyCancel);
        [self.view showHUDFailTips:@"加载失败,请稍后重试!" hideDelay:1];
        if (self.isFromADGuide) {//广告页加载失败
            [(AppDelegate *)UIApplication.sharedApplication.delegate setRootVCForKeyWindowAnimation:YES tabbarSelectedIndex:0];
            return;
        }
        [self performSelector:@selector(popTheVC) withObject:nil afterDelay:1];
    }
}

/**
 无网络等原因加载失败
  */
- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(null_unspecified WKNavigation *)navigation withError:(NSError *)error{
    [self.view showHUDFailTips:@"加载失败,请稍后重试!" hideDelay:1];
    if (self.isFromADGuide) {//广告页加载失败
        [(AppDelegate *)UIApplication.sharedApplication.delegate setRootVCForKeyWindowAnimation:YES tabbarSelectedIndex:0];
        return;
    }
    [self performSelector:@selector(popTheVC) withObject:nil afterDelay:1];
}

//MARK:交互
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message{
    
    if ([message.name isEqualToString:@"appToIndex"]){
        // 首页
        self.tabBarController.selectedIndex = 0;
        [self.navigationController popToRootViewControllerAnimated:YES];
        
    }else if ([message.name isEqualToString:@"appToLogin"]){
        // 跳转登录页
        [self presentViewController:LogInVC animated:YES completion:nil];
        
    }else if ([message.name isEqualToString:@"appToRegister"]){
        // 跳转注册页
        [self presentViewController:LogInVC animated:YES completion:nil];

        
    }else if([message.name isEqualToString:@"appToRealName"]){
        // 跳转实名认证页
        InvestPrepareVC *prepare = [InvestPrepareVC new];
        [self.navigationController pushViewController:prepare animated:YES];
        
    }else if([message.name isEqualToString:@"appToRecharge"]){
        // 跳转充值页
        
        [self.navigationController pushViewController:[[UIStoryboard storyboardWithName:@"Profile" bundle:nil] instantiateViewControllerWithIdentifier:@"RechargeViewControllerID"] animated:YES withHideBottomBarWhenPush:YES pop:NO];
        
    }else if ([message.name isEqualToString:@"appToGetList"]){
        // 跳转产品列表页
        [self backPop:self.isFromADGuide tabBarIndex:1];

    }else if ([message.name isEqualToString:@"appAcceptVal"]){
        // 请求APP的传值
    }else if ([message.name isEqualToString:@"appPassVal"]){
        // 向APP传值并关闭当前webView窗口
        [self backPop:self.isFromADGuide tabBarIndex:0];
        
    }else if ([message.name isEqualToString:@"appOpenLoading"]){
        // 打开app的loading
    }else if ([message.name isEqualToString:@"appCloseLoading"]){
        // 关闭app的loading
        
    }else if ([message.name isEqualToString:@"appOpenView"]){
        // 打开新的webView窗口
        NSLog(@"%@",message.body);
        NSDictionary *strDic = [message.body mj_JSONObject];
        BannerWebViewVC *webVC = [[BannerWebViewVC alloc] initWithUrlStr:[NSString stringWithFormat:@"%@",strDic[@"url"]] title:strDic[@"title"]];
        webVC.isFromADGuide = self.isFromADGuide;
        [self.navigationController pushViewController:webVC animated:YES withHideBottomBarWhenPush:YES pop:YES];
    }else if ([message.name isEqualToString:@"appCloseView"]){
        // 关闭webView窗口
        if (_isFromADGuide) {
            [self backPop:YES tabBarIndex:0];
            return;
        }
        [self.navigationController popViewControllerAnimated:true];

    }else if ([message.name isEqualToString:@"appToShare"]){
        // App分享功能
        NSString *accountStatus = [WLFileManager readUserDataForKey:kUserSessionId];
        
        if (accountStatus.length<1) {
            [self.navigationController presentViewController:LogInVC animated:YES completion:nil];
            return;
        }

        
        /// 邀请好友
        [self pushVC:[[JCWInviteFirendVC alloc] init]];
        
    }else if ([message.name isEqualToString:@"appToAccount"]){
        [self backPop:self.isFromADGuide tabBarIndex:2];
    }else if ([message.name isEqualToString:@"appToRiskAssessment"]){
        // 风险测评 未登录 跳登录 已经测评 跳测评结果页
        NSInteger userLevel = [[WLFileManager readUserDataForKey:kUserLevel] integerValue];
        NSString *accountStatus = [WLFileManager readUserDataForKey:kUserSessionId];
        if (accountStatus.length<1) {
            [self.navigationController presentViewController:LogInVC animated:YES completion:nil];
            return;
        }
        if (userLevel == 0) {//未设置跳转答题界面
            
            RiskAppraiseViewC *riskVC = [RiskAppraiseViewC new];
            [self.navigationController pushViewController:riskVC animated:YES];
            
        }else{///直接跳转展示结果页
            JCWRiskAssessmentResultVC * vc = [[JCWRiskAssessmentResultVC alloc] init];
            vc.typeIndex = userLevel;
            [self.navigationController pushViewController:vc animated:YES];
        }
        
        
    }else if ([message.name isEqualToString:@"appEnlarge"]){
        self.photoUrl = [NSURL URLWithString:message.body];
  
        self.photoBrowser.view.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.4];
        self.photoBrowser.modalPresentationStyle = UIModalPresentationOverCurrentContext;
        [self presentViewController:_photoBrowser animated:YES completion:nil];
    }else if ([message.name isEqualToString:@"appShare"]){
        NSLog(@"---- %@",message);
        NSDictionary *shareDic = [message.body mj_JSONObject];
        NSString *title = shareDic[@"title"];
        NSString *description = shareDic[@"description"];
        NSString *url = shareDic[@"url"];
        NSString *icon = shareDic[@"icon"];
        JCWShareVC *vc = [[JCWShareVC alloc]init];
        vc.shareTitle = title;
        vc.shareDescription = description;
        vc.shareUrl = url;
        vc.shareImageUrl = icon;
        vc.modalPresentationStyle = UIModalPresentationOverCurrentContext;
        WLGetWeakSelf(weakSelf, self);
        vc.shareResultHandler = ^(NSString * _Nonnull resultStr) {
//            weakSelf.view.showHUDWarnTips(resultStr, hideDelay: kHUDHideDelay)
            [weakSelf.view showHUDFailTips:resultStr hideDelay:kHUDHideDelay];
        };
        [self presentViewController:vc animated:true completion:nil];
        
    }
    
}

///退出当前页
- (void)backPop:(BOOL)isFromADGuide tabBarIndex:(NSInteger)index {
    if (isFromADGuide) {
        [(AppDelegate *)UIApplication.sharedApplication.delegate setRootVCForKeyWindowAnimation:isFromADGuide tabbarSelectedIndex:index];
    }else{
        self.tabBarController.selectedIndex = index;
        [self.navigationController popViewControllerAnimated:YES];
    }
    
    
}

- (void)hideProgress{
    self.progressView.hidden = YES;
    self.progressView.progress = 0;
}

///进度条
- (UIProgressView *)progressView{
    if (!_progressView) {
        
        CGFloat statusH = [[UIApplication sharedApplication] statusBarFrame].size.height;

        CGFloat ty = [self.url containsString:@"mixApp"] ?statusH:kJcwGetNavHeight();
        _progressView = [[UIProgressView alloc] initWithFrame:(CGRect){{0,ty},{self.view.frame.size.width,1}}];
        _progressView.progress = 0.01;
        _progressView.progressViewStyle = UIProgressViewStyleBar;
        _progressView.progressTintColor = Normal_RedColor;
    }
    return _progressView;
}


//HTML页面Alert出内容
- (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler{
    
    UIAlertController * alert = [UIAlertController alertControllerWithTitle:webView.title message:message preferredStyle:UIAlertControllerStyleAlert];
    
    [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        completionHandler();
    }]];
    [self presentViewController:alert animated:YES completion:nil];
    
}
//HTML页面弹出Confirm时调用此方法
- (void)webView:(WKWebView *)webView runJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(BOOL))completionHandler{
    
    UIAlertController * alert = [UIAlertController alertControllerWithTitle:webView.title message:message preferredStyle:UIAlertControllerStyleAlert];
    
    [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        completionHandler(YES);
    }]];
    
    [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        completionHandler(NO);
    }]];
    [self presentViewController:alert animated:YES completion:nil];
}

- (NSInteger)numberOfPagesInViewController:(PBViewController *)viewController {
    return 1;
}

- (void)viewController:(PBViewController *)viewController didSingleTapedPageAtIndex:(NSInteger)index presentedImage:(UIImage *)presentedImage
{
    [viewController dismissViewControllerAnimated:YES completion:nil];
}

- (UIImage *)viewController:(PBViewController *)viewController imageForPageAtIndex:(NSInteger)index
{
//    do {
//        NSData *data =
//    } while (<#condition#>);
//            do {
//                let data : NSData = try NSData(contentsOf: photoUrl!)
//                return UIImage(data: data as Data)
//
//            } catch  {
//                return UIImage(named: "")
//
//            }
    UIImage *img = [[UIImage alloc] initWithData:[NSData dataWithContentsOfURL:_photoUrl]];

    return img;
}
@end
